//test.js  
//获取应用实例  
const formatTime = require('../../../utils/formatTime')
const db = wx.cloud.database()
var app = getApp()
const user = db.collection('user')
Page({
  data: {
    imgUrls: [],
    comment_list: [],
    //回复数据
    comment_list2: [],
    text: '', //文章
    time: '', //时间
    dz: [], //点赞的数组
    follow: [], //该文章用户的粉丝
    _id: '', //文章_id
    /*定义一些数据*/
    focus: false, //输入框是否聚焦
    placeholder: '说点什么...', //底部输入框占字符
    placeholder2: '说点什么，让ta也认识看笔记的你', //顶部输入框占字符
    value: null, //顶部输入框内容
    comment_text: null, //底部评论框内容
    /*
     *以下初始化数据是用户点击任意一条评论或回复时需要设置的数据
     *然后将设置好的数据传递给评论时新创建的评论数据对象
     */
    now_reply_name: null, //当前点击的评论或回复评论的用户昵称
    now_reply_type: 0, //当前回复类型 默认为0 1为回复评论 2为回复回复
    now_parent_id: 0, //当前点击的评论或回复评论的所属评论id
    now_reply: 0, //当前点击的评论或回复评论的id


    nickName: '', //本人昵称
    avatarUrl: '', //本人头像
    in_nickName: '', //昵称
    in_avatarUrl: '', //头像
    in_openid: '', //
    indicatorDots: true,
    autoplay: false,
    interval: 500,
    duration: 100,
    flow: '关注',
    flowc: '#CC3333',
    dianzan: 'aixin.png',
  },
  async flown() {
    let {
      flow,
      follow,
      openid,
      in_openid
    } = this.data
    if (flow == '已关注') {
      flow = '关注';
      follow.splice(follow.indexOf(openid), 1)
      console.log(follow.indexOf(openid))
      console.log(follow)
    } else {
      flow = '已关注'
      if(follow.indexOf(openid)==-1){
        console.log(openid)
        console.log(follow)
      follow.push(openid)
      }
      console.log(follow)
    }
    this.setData({
      flow,
      follow
    })
    let res = await wx.cloud.callFunction({
      name: 'upFollow',
      data: {
        openid,
        in_openid,
        follow
      }
    })


  },
  async dianzan() { //点赞
    let check = this.checkLogin()
    console.log(check)
    if (!check) {
      return
    }
    let {
      dianzan,
      dz,
      openid,
      _id
    } = this.data
    if (dianzan == 'dianzan.png') {
      dianzan = 'aixin.png';
      dz.splice(dz.indexOf(openid), 1)
      console.log(dz.indexOf(openid))
      console.log(dz)
    } else {
      dianzan = 'dianzan.png'
      dz.push(openid)
      console.log(dz)
    }
    this.setData({
      dianzan: dianzan,
      dz
    })
    let res = await wx.cloud.callFunction({
      name: 'upCommentZan',
      data: {
        _id: _id,
        dz: dz
      }
    })
    console.log(res)
  },
  async onLoad(option) { //初始化
    wx.showLoading({
      title: '努力加载中...',
      mask:true
    })
    console.log('传值',option)
    this.setData({
      isCenter:option.center
    })
    let openid = app.globalData.openid
    let res = await wx.cloud.callFunction({ //获取云函数的数据
      name: 'getFoodComment',
      data: {
        _id: option._id,
        openid: openid
      }
    })
    if (res.result.getInComment[0]) { //获取评论
      let comment_list = res.result.getInComment
      comment_list.forEach(v => {
        v.comment_time = formatTime.formatTime(v.comment_time)
      })
      console.log(comment_list)
      this.setData({
        comment_list: res.result.getInComment
      })
    }
    if (res.result.getInComment2[0]) { //获取回复
      let comment_list2 = res.result.getInComment2
      comment_list2.forEach(v => {
        v.comment_time = formatTime.formatTime(v.comment_time)
      })
      console.log(comment_list2)
      this.setData({
        comment_list2: res.result.getInComment2
      })
    }
    console.log(res)
    this.setData({
      _id: res.result.getComment._id,
      imgUrls: res.result.getComment.imgUrl,
      text: res.result.getComment.text,
      time: res.result.getComment.time,
      nickName: app.globalData.nickName,
      avatarUrl: app.globalData.avatarUrl,
      dz: res.result.getComment.dz,
      in_nickName: res.result.getComment.nickName,
      in_avatarUrl: res.result.getComment.avatarUrl,
      in_openid: res.result.getComment.openid,
      dianzan: res.result.dianzan,
      openid: app.globalData.openid,
      flow: res.result.flow,
      follow: res.result.follow
    })
    wx.hideLoading()
  },
  replyComment(e) {
    var cid = e.currentTarget.dataset.cid; //当前点击的评论id
    var name = e.currentTarget.dataset.name; //当前点击的评论昵称
    var pid = e.currentTarget.dataset.pid; //当前点击的评论所属评论id
    var type = e.currentTarget.dataset.type; //当前回复类型
    this.setData({
      focus: true, //输入框获取焦点
      placeholder: '回复' + name + '：', //更改底部输入框占字符
      now_reply: cid, //当前点击的评论或回复评论id
      now_reply_name: name, //当前点击的评论或回复评论的用户名
      now_parent_id: pid, //当前点击的评论或回复评论所属id
      now_reply_type: type, //获取类型(1回复评论/2回复-回复评论)
    })
  },
  async delcomment(e){   //删除此评论
    let that =this
    console.log('e',e)
    let nickName=e.currentTarget.dataset.name
    let res=await wx.showModal({
      title: '你确定删除这条笔记吗？',
      confirmColor:'#f00',
      cancelText: '取消',
      confirmText: '确定'
      })
    if(res.confirm){
      that.del(nickName)
    }

  },
  async del(e){
    let isCenter=this.data.isCenter
    console.log('删除传值',isCenter)

    let url='../comment'
    if(isCenter=='true'){
      url='../../center/center'
      console.log('是')
    }
    let _id = this.data._id
    let res = await wx.cloud.callFunction({
      name:'delFoodComment',
      data:{_id}
    })
			if(res.result){
				wx.showToast({
          title: '成功',
          icon:'success',
          success: function () {
            setTimeout(function() {
              wx.reLaunch({
                url:url,
              })
            }, 1000);
          }
        })
			}else{
				wx.showToast({
          title: '删除失败',
          icon:'error'
        })
			}
			
  },
  previewImg(e){  //点击预览图片
    console.log('点击预览图片：',e);
    let imgUrls = this.data.imgUrls
    var id = e.currentTarget.dataset.id
    wx.previewImage({
      current:imgUrls[id],
      urls:imgUrls
    })
  },
  //底部输入框提交内容时触发
  async confirm(e) {
    let check = this.checkLogin()
    console.log(check)
    if (!check) {
      return
    }
    //获取输入框输入的内容
    var comment_text = e.detail.value;
    console.log(e.detail.value)
    //判断用户是否输入内容为空
    if (comment_text == '') {
      //用户评论输入内容为空时弹出
      wx.showToast({
        title: '请输入内容', //提示内容
        icon: 'error' //提示图标
      })
    } else {
      var that = this
      var date = new Date(); //创建时间对象
      var hour = date.getHours(); //获取时      
      var minute = date.getMinutes(); //获取分          
      var time = `${hour}:${minute}`; //当前时间
      var comment_user_name = this.data.nickName //用户昵称      
      var comment_user_avatar = this.data.avatarUrl //用户头像
      var reply_name = null; //回复评论用户的昵称
      var parent_id = 0; //评论所属哪个评论的id
      var reply_id = Number(this.data.now_reply_type); //回复谁的评论id
      //通过回复谁的评论id判断现在是评论还是回复
      if (reply_id != 0) {
        //现在是回复
        var reply_type = this.data.now_reply_type; //回复类型
        //通过回复类型判断是回复评论还是回复回复
        if (reply_type == 1) {
          //回复评论
          parent_id = this.data.now_parent_id; //回复评论所属评论id
          reply_name = this.data.now_reply_name; //回复评论用户昵称
        } else {
          //回复回复
          parent_id = this.data.now_parent_id; //回复评论所属评论id
          reply_name = this.data.now_reply_name; //回复评论用户昵称
        }
      } else {
        //现在是评论
      }
      var comment_detail = { //评论/回复对象
        comment_pr_id: this.data._id, //评论Id      
        comment_user_name: comment_user_name, //用户昵称      
        comment_user_avatar: comment_user_avatar, //用户头像      
        comment_text: comment_text, //评论内容      
        comment_time: time, //评论时间      
        reply_id: reply_id, //回复谁的评论的id      
        parent_id: parent_id, //评论所属哪个评论id      
        reply_name: reply_name //回复评论人的昵称
      }
      console.log(comment_detail)
      //判断parent_id是否为0 为0就是评论 不为0就是回复
      let res = await wx.cloud.callFunction({
        name: 'addInComment',
        data: {
          comment_detail: comment_detail
        }
      })
      console.log('addInComment:', res)
      comment_detail._id = res.result.Msg._id
      if (comment_detail.parent_id != 0) {
        //回复
        var comment_list2 = that.data.comment_list2; //获取回复数据    
        comment_list2.push(comment_detail);
        console.log(comment_list2)
        this.setData({
          comment_list2
        })
      } else {
        //评论
        var comment_list = that.data.comment_list; //获评论数据
        comment_list.push(comment_detail);
        console.log(comment_list)
        this.setData({
          comment_list
        })
      }

      //动态渲染
      this.setData({
        //发表评论后将以下数据初始化 为下次发表评论做准备
        comment_text: null, //评论内容        
        now_reply: 0, //当前点击的评论id        
        now_reply_name: null, //当前点击的评论的用户昵称        
        now_reply_type: 0, //评论类型        
        now_parent_id: 0, //当前点击的评论所属哪个评论id        
        placeholder: "说点什么...", //输入框占字符
        //将加入新数据的数组渲染到页面        
      })
    }
  },
  checkLogin() { //检查登陆
    let openid = app.globalData.openid
    let that = this
    if (!openid) {
      console.log('未登陆')
      wx.showModal({
        title: '你还未登陆',
        content: '请先登陆',
        cancelText: '取消',
        confirmText: '登陆',
        success(res) {
          if (res.confirm) {
            console.log('点了确定')
            that.login()
          }
        }
      })
      return false
    } else {
      console.log('已登陆')
      return true
    }
  },
  async login() { //登陆
    console.log(app.globalData.nickName)
    let _id = this.data._id
    let res = await wx.getUserProfile({
      desc: 'desc',
    })
    console.log('res:', res)
    let {
      avatarUrl,
      nickName
    } = res.userInfo
    res = await wx.cloud.callFunction({
      name: 'login',
      data: {
        avatarUrl,
        nickName
      }
    })
    console.log('登陆结果', res)
    if (res.result.nickName) {
      wx.showToast({
        title: '登陆成功',
      })
      let openid = await user.where({
          nickName: nickName,
          avatarUrl: avatarUrl
        })
        .get()
      openid = openid.data[0].openid
      console.log('openid', openid)
      //写入用户数据到客户端↓↓↓
      this.setData({
        avatarUrl: res.result.avatarUrl,
        nickName: res.result.nickName,
        openid
      })
      wx.setStorage({
        key: 'user',
        data: {
          'avatarUrl': avatarUrl,
          'nickName': nickName,
          'openid': openid
        }
      })
      app.globalData.avatarUrl = avatarUrl
      app.globalData.nickName = nickName
      app.globalData.openid = openid
      console.log(app.globalData.nickName)
      console.log(app.globalData.openid)
    } else {
      wx.showToast({
        title: '登陆失败',
        icon: 'error'
      })
    }
  },
})